<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <el-descriptions direction="vertical" :column="10" border>
      <el-descriptions-item
        v-for="(item, index) in tagArr"
        :key="index"
        :type="item.type"
        :label="item.label"
      >
        {{ item.value }}{{ item.unit }}
      </el-descriptions-item>
      >
    </el-descriptions>
    <!-- <el-row>
      <el-col class="tag-area" :span="24">
        <el-tag
          v-for="(item, index) in tagArr"
          :key="index"
          size="medium"
          :type="item.type"
        >
          {{ item.label }}{{ item.value }}{{ item.unit }}
        </el-tag>
      </el-col>
    </el-row> -->
    <lb-table
      class="mt10"
      ref="excelTable"
      :merge="mergeArr"
      :column="tableData.column"
      :data="tableData.data"
      border
      :height="600"
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
  </lb-layout>
</template>

<script>
import { deepClone, dealElectricity, saveQuery, outQuery } from "@/utils/index";
import { getparkList } from "@/api/park/parkmsg.js";
import { getbuildingList } from "@/api/park/buildingmsg.js";
import { getfloorList } from "@/api/park/floormsg.js";
import {
  parkBuildingFloorEnergyStatisticList,
  parkBuildingFloorEnergyStatistic,
} from "@/api/statistics/park.js";
import { exportExcel } from "@/utils/xlsx";

export default {
  name: "",
  components: {},
  dicts: [],
  data() {
    return {
      mergeArr: ["year"],
      tagArr: [
        {
          label: "楼宇数量",
          value: 0,
          unit: "家",
          type: "success",
        },
        {
          label: "楼层数量",
          value: 0,
          unit: "层",
          type: "success",
        },
        {
          label: "用能面积",
          value: 0,
          unit: "㎡",
          type: "success",
        },
        {
          label: "单位数量",
          value: 0,
          unit: "家",
          type: "success",
        },
        {
          label: "房间数量",
          value: 0,
          unit: "间",
          type: "success",
        },
        {
          label: "用能人数",
          value: 0,
          unit: "人",
          type: "success",
        },
        {
          label: "总电耗",
          value: 0,
          unit: "kwh",
          type: "danger",
        },
        {
          label: "总水耗",
          value: 0,
          unit: "t",
          type: "danger",
        },
        {
          label: "总碳排",
          value: 0,
          unit: "kgCO2",
          type: "danger",
        },
        {
          label: "实际费用",
          value: 0,
          unit: "元",
          type: "warning",
        },
      ],
      parkList: [],
      buildingList: [],
      floorList: [],
      disabledF: true,
      disabledF2: true,
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            year: {
              label: "统计年份:",
              typeName: "el-date-picker",
              type: "year",
              size: "small",
              "value-format": "yyyy",
              placeholder: "请选择统计年份",
              clearable: false,
              "picker-options": {
                disabledDate(time) {
                  let date = new Date();
                  return time.getFullYear() > date.getFullYear();
                },
              },
            },
            parkId: {
              label: "区域名称:",
              render: (h) => {
                let that = this;
                let arr = [...that.parkList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().parkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择区域",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("parkId", value);
                          that.$refs?.form?.setFieldValue("buildId", null);
                          that.$refs?.form?.setFieldValue("floorId", null);
                          if (value && String(value).length > 0) {
                            that.disabledF = false;
                          } else {
                            that.disabledF = true;
                          }
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            buildId: {
              label: "楼宇名称:",
              render: (h) => {
                let that = this;
                let arr = [...that.buildingList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().buildId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼宇",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                        disabled: that.disabledF,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("buildId", value);
                          that.$refs?.form?.setFieldValue("floorId", null);
                          if (value && String(value).length > 0) {
                            that.disabledF2 = false;
                          } else {
                            that.disabledF2 = true;
                          }
                          that.$forceUpdate();
                        },
                        "visible-change": (value) => {
                          if (value) {
                            that.requestBuildinglist();
                          }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            floorId: {
              label: "楼层名称:",
              render: (h) => {
                let that = this;
                let arr = [...that.floorList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().floorId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼层",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                        disabled: that.disabledF2,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("floorId", value);
                          that.$forceUpdate();
                        },
                        "visible-change": (value) => {
                          if (value) {
                            that.requestFloorList();
                          }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "导出",
              typeName: "el-button",
              plain: true,
              type: "warning",
              size: "small",
              icon: "el-icon-download",
              click: this.handleExport,
            },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            prop: "year",
            label: "年份",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "parkName",
            label: "区域名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "buildingName",
            label: "楼宇名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "floorName",
            label: "楼层名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "floorArea",
            label: "楼层用能面积(㎡)",
            minWidth: 140,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "㎡";
              let value = scope.row.floorArea ?? 0;
              value = dealElectricity(value, 1, 2);
              let a = value + unit;
              return <div>{value}</div>;
            },
          },
          {
            prop: "peopleNum",
            label: "用能人数",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "roomNum",
            label: "房间数量",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "deptNum",
            label: "单位数量",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "",
            label: "人均电耗(kwh)",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "kwh";
              let personalAvgKwh = scope?.row?.personalAvgKwh ?? 0;
              let value = dealElectricity(personalAvgKwh, 1, 2);
              let a = value + unit;
              return <div>{value}</div>;
            },
          },
          {
            prop: "",
            label: "人均水耗(t)",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "t";
              let personalAvgWater = scope?.row?.personalAvgWater ?? 0;
              let value = dealElectricity(personalAvgWater, 1000, 2);
              let a = value + unit;
              return <div>{value}</div>;
            },
          },
          // {
          //   prop: "",
          //   label: "人均碳排(kgCO2)",
          //   minWidth: 100,
          //   align: "center",
          //   showOverflowTooltip: true,
          //   render: (h, scope) => {
          //     let unit = "kgCO2";
          //     let personalAvgCo2 = scope?.row?.personalAvgCo2 ?? 0;
          //     let value = dealElectricity(personalAvgCo2, 1, 2);
          //     let a = value + unit;
          //     return <div>{value}</div>;
          //   },
          // },
          {
            prop: "",
            label: "总电耗(kwh)",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "kwh";
              let kwhTotal = scope?.row?.kwhTotal ?? 0;
              let value = dealElectricity(kwhTotal, 1, 2);
              let a = value + unit;
              return <div>{value}</div>;
            },
          },
          {
            prop: "",
            label: "总水耗(t)",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "t";
              let waterTotal = scope?.row?.waterTotal ?? 0;
              let value = dealElectricity(waterTotal, 1000, 2);
              let a = value + unit;
              return <div>{value}</div>;
            },
          },
          {
            prop: "",
            label: "总碳排(kgCO2)",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "kgCO2";
              let co2Total = scope?.row?.co2Total ?? 0;
              let value = dealElectricity(co2Total, 1, 2);
              let a = value + unit;
              return <div>{value}</div>;
            },
          },
          {
            prop: "",
            label: "实际费用(元)",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "元";
              let feeTotal = scope?.row?.feeTotal ?? 0;
              let value = dealElectricity(feeTotal, 1, 2);
              let a = value + unit;
              return <div>{value}</div>;
            },
          },
          {
            label: "操作",
            width: "120",
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  v-hasPermi={[
                    "parkManage:park:building:floor:statistic:detail",
                  ]}
                  onClick={() => {
                    let obj = {
                      year: that.$refs?.form?.getFieldsValue().year,
                      parkId: that.$refs?.form?.getFieldsValue().parkId,
                      buildId: that.$refs?.form?.getFieldsValue().buildId,
                      floorId: that.$refs?.form?.getFieldsValue().floorId,
                    };
                    saveQuery("floorstatisticssticssearchQuery", obj);
                    that.$router.push({
                      name: "statisticsFloorDetail",
                      query: {
                        year: scope?.row?.year ?? "未知年份",
                        parkName: scope?.row?.parkName ?? "未知园区",
                        buildingName: scope?.row?.buildingName ?? "未知楼幢",
                        floorName: scope?.row?.floorName ?? "未知楼层",
                        parkId: scope.row.parkId,
                        buildId: scope.row.buildingId,
                        floorId: scope.row.floorId,
                      },
                    });
                  }}
                >
                  详情
                </el-button>
              );
              return <div>{a}</div>;
            },
          },
        ],
        data: [],
      },
      fromRouter: "",
    };
  },
  created() {
    this.requestParklist();
    this.requestBuildinglist();
    this.requestFloorList();
  },
  mounted() {
    this.choseFullYear();
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromRouter = from?.path ?? "";
    });
  },
  methods: {
    choseFullYear() {
      let year = new Date().getFullYear();
      year = String(year);
      this.$nextTick(() => {
        let form = {
          ...outQuery("floorstatisticssticssearchQuery", this.fromRouter, [
            "/statistics/parkS/floor/detial",
          ]),
        };
        if (Object.keys(form).length > 0) {
          this.$refs?.form?.setFieldValue("year", form?.year ?? year);
          this.$refs?.form?.setFieldValue("parkId", form?.parkId ?? null);
          if (form.buildId || form.buildId == 0) {
            if (form.floorId || form.floorId == 0) {
              this.requestBuildinglist();
              this.$nextTick(() => {
                this.$refs?.form?.setFieldValue("buildId", form.buildId);
                this.requestFloorList(form.floorId);
              });
            } else {
              this.requestBuildinglist(form.buildId);
            }
          } else {
            this.handlerSearchDetail();
          }
        } else {
          this.$refs?.form?.setFieldValue("year", year);
          this.handlerSearchDetail();
        }
      });
    },
    // 园区集合
    requestParklist() {
      this.parkList = [];
      getparkList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.parkList.push(obj);
            });
          }
        })
        .catch((err) => {
          // // this.$message.error("系统错误,请联系管理员!401001");
        });
    },
    // 楼宇集合
    requestBuildinglist(backid) {
      this.buildingList = [];
      let params = {};
      let parkId = this.$refs?.form?.getFieldsValue().parkId;
      if (String(parkId).length > 0) {
        params.parkId = parkId;
      }
      getbuildingList(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.buildingList.push(obj);
            });
            if (backid || backid == 0) {
              this.$refs?.form?.setFieldValue("buildId", backid);
              this.disabledF = false;
              this.$nextTick(() => {
                this.handlerSearchDetail();
              });
            }
          }
        })
        .catch((err) => {
          // // this.$message.error("系统错误,请联系管理员!402001");
        });
    },
    // 楼层集合
    requestFloorList(backid) {
      this.floorList = [];
      let params = {};
      let parkId = this.$refs?.form?.getFieldsValue().parkId;
      let buildId = this.$refs?.form?.getFieldsValue().buildId;
      if (String(parkId).length > 0) {
        params.parkId = parkId;
      }
      if (String(buildId).length > 0) {
        params.buildingId = buildId;
      }
      getfloorList(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let floorName = item?.name ?? "";
              let buildingName = item?.buildingName ?? "";
              let obj = {
                label: buildingName + "-" + floorName,
                value: item?.id,
              };
              this.floorList.push(obj);
            });
            if (backid || backid == 0) {
              this.$refs?.form?.setFieldValue("floorId", backid);
              this.disabledF = false;
              this.disabledF2 = false;
              this.$nextTick(() => {
                this.handlerSearchDetail();
              });
            }
          }
        })
        .catch((err) => {
          // // this.$message.error("系统错误,请联系管理员!403001");
        });
    },
    requestTotal(data) {
      let that = this;
      let query = {
        ...data,
      };
      parkBuildingFloorEnergyStatistic(query)
        .then((res) => {
          console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let result = res?.data ?? {};
          this.tagArr[0].value = result?.buildingNum ?? 0;
          this.tagArr[1].value = result?.floorNum ?? 0;
          this.tagArr[2].value = dealElectricity(result?.buildArea ?? 0, 1, 2);
          this.tagArr[3].value = result?.deptNum ?? 0;
          this.tagArr[4].value = result?.roomNum ?? 0;
          this.tagArr[5].value = result?.peopleNum ?? 0;
          this.tagArr[6].value = dealElectricity(result?.kwhTotal ?? 0, 1, 2);
          this.tagArr[7].value = dealElectricity(
            result?.waterTotal ?? 0,
            1000,
            2
          );
          this.tagArr[8].value = dealElectricity(result?.co2Total ?? 0, 1, 2);
          this.tagArr[9].value = dealElectricity(result?.feeTotal ?? 0, 1, 2);
        })
        .catch(() => {
          // // this.$message.error("系统错误,请联系管理员!");
        });
    },
    async initData(data) {
      let that = this;
      let query = {
        ...data,
      };
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await parkBuildingFloorEnergyStatisticList(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 搜索
    handlerSearchDetail() {
      const { ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
      };
      this.initData(data);
      this.requestTotal(data);
    },
    // 重置
    handleReset() {
      this.disabledF = true;
      this.disabledF2 = true;
      this.$refs?.form?.resetFields();
      this.choseFullYear();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleExport() {
      if (this.floorList.length <= 0) {
        this.$message.warning("无数据内容导出,请确认!");
        return;
      }
      let user = this.$store.state.user;
      let deptName = user?.deptName ?? "未知单位名称";
      let fileName = deptName + "-" + "楼层统计";
      let cols = [{ wpx: 240 }];
      exportExcel(this.$refs.excelTable, fileName, cols);
    },
  },
};
</script>

<style lang="scss" scoped>
.tag-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .el-tag {
    margin-right: 10px;
  }
}
::v-deep .el-descriptions-item__cell {
  text-align: center !important;
}
</style>
